# -*- coding: UTF-8 -*-
import os, datetime,time
import requests

'''
通过url读取服务器数据，并写入本地文件夹
'''
#log
LOG_ADD='/usr/local/tomcat7/webapps/ROOT/logs/meteo_getpic.txt'
# LOG_ADD='F:/Share/awitNcFile/meteo_getpic.txt'
#路线数据
DATA_CONFIG={
    'guiyang':'http://113.106.88.29/wrf_yuqian/pic/guiyang_{0}_{1}.png',
    'zunyi':'http://113.106.88.29/wrf_yuqian/pic/zunyi_{0}_{1}.png',
    'chongqing':'http://113.106.88.29/wrf_yuqian/pic/chongqing_{0}_{1}.png',
    'hefei':'http://183.57.41.102/wrf_lusuwan/pic/lusuwan_{0}_{1}.png'
}
#气象类型 雨量/雪量/能见度/温度/风/凝冻
weather_type=['temp','rain','wind','freez','vis','snow']

'''
根据路线，灾害，时间获取气象图
'''
def getMeteoPic(roadCode,disType,time_name):
    img_url=DATA_CONFIG[roadCode].format(disType,time_name)
    file_path = '/mnt/ftp/meteoftp/' + roadCode+'/'+disType
    # file_path = 'F:\\Share\\awitNcFile\\' + roadCode+'\\'+disType #图片存取路径
    file_name = disType + '_' + time_name  #图片名称
    try:
        # 是否有这个路径
        if not os.path.exists(file_path):
        #     # 创建路径
            os.makedirs(file_path)
        # 获得图片后缀
        file_suffix = os.path.splitext(img_url)[1]
        # print(file_suffix)
        # 拼接图片名（包含路径）
        filename = '{}{}{}{}'.format(file_path, os.sep, file_name, file_suffix)
        print(filename)
    except IOError as e:
        print("IOError")
    except Exception as e:
        print("Exception")

    html = requests.get(img_url)
    if html.status_code == 200:
        with open(filename, 'wb') as file:
            file.write(html.content)
    with open(LOG_ADD, 'ab') as f:
        f.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '：get '+ str(roadCode)+' '+ file_name + ' succ!\n')

'''
获取48小时内的图片
'''
def loadPic(roadCode):
    for i in range(48):
        time_name = (datetime.datetime.now() + datetime.timedelta(hours=i)).strftime("%Y%m%d%H")
        for wtype in weather_type:
            getMeteoPic(roadCode,wtype,time_name)

'''
遍历路线获取图片
'''
for road in DATA_CONFIG:
    loadPic(road)


